const jsonfile = require('jsonfile');
const moment = require('moment');
const {orderTimeLimit,orderTimeMap} = require('../bin/config');
const {flatten,isArray,set,sortBy,isUndefined,compact,difference,concat,cloneDeep,uniqBy} =require('loadsh')
const {setLog} =require('../util/log')
const {setNotify} =require('../util/notify')
/*const util = require('util');
const setTimeoutPromise  = util.promisify(setTimeout);*/
module.exports = {
    '/': (req, res) => {
        //搜索 type 0今日,
        const {username = '', create_time} = req.query
        const today = create_time || moment().format('YYYY_MM_DD');
        // createTime
        //充值完毕再次下单清空余额信息
        try {
            const listObject = jsonfile.readFileSync(`data/order/${today}.json`)
            const result = Object.values(listObject).filter(i =>i.username.includes(username))
            res.send({
                code: 0,
                data: result,
                msg: '请求成功'
            });
        } catch {
            res.send({
                code: 0,
                data: [],
                msg: '请求成功'
            });
        }
    },
    '/log': (req, res) => {
        const {username = '', create_time} = req.query
        const today = create_time || moment().format('YYYY_MM_DD');
        try {
            const listObject = jsonfile.readFileSync(`data/order/${today}.json`)
            const result = Object.values(listObject).filter(i =>i.username.includes(username)).map(i => concat(i.balanceInfo || [],i.logs || []));
            res.send({
                code: 0,
                data: sortBy(flatten(result),'create_time').reverse(),
                msg: '请求成功'
            });
        } catch {
            res.send({
                code: 0,
                data: [],
                msg: '请求成功'
            });
        }
    },
    '/setStatus': (req, res) => {
        //读写文件
        const {status, senduser,username} = req.body;
        const today = moment().format('YYYY_MM_DD');
        const listObject = jsonfile.readFileSync(`data/order/${today}.json`);
        listObject[senduser].status = status;
        //异常信息写入文件中
        //刷新global.orderStatus被清空
        if(status){
            if(global.orderStatus[senduser]){
                clearTimeout(global.orderStatus[senduser].delayTime);
                delete global.orderStatus[senduser];
            }
        }
        //延迟执行
        jsonfile.writeFileSync(`data/order/${today}.json`,listObject)
        res.send({
            code: 0,
            msg: status?'锁定成功':'解锁成功'
        })
    },
    '/countDown': (req, res) => {
        const today = moment().format('YYYY_MM_DD');
        const { senduser} = req.query;
        if(!global.orderStatus[senduser]){
            global.orderStatus[senduser]={
                startTime:(new Date()).getTime(),
                delayTime:setTimeout(() => {
                    const listObject = jsonfile.readFileSync(`data/order/${today}.json`);
                    listObject[senduser].status=1;
                    jsonfile.writeFileSync(`data/order/${today}.json`,listObject);
                    delete global.orderStatus[senduser];
                },orderTimeLimit)
            }
        }
        res.send({
            code: 0,
            data:{
                orderTimeLimit,
                startTime:global.orderStatus[senduser] && global.orderStatus[senduser].startTime || 0
            },
            msg: '倒计时开启',
        })
    },
    '/refuse':(req, res)=>{
        let {platform,msg,username}=req.body;
        if(!platform || !username) return res.send({code:1,msg:'平台和用户名不能为空'});
        const today = moment().format('YYYY_MM_DD');
        const listObject = jsonfile.readFileSync(`data/order/${today}.json`)
        listObject[username].isAudit=listObject[username].isAudit.map(i=>i?i:2);
        listObject[username].status=0
        const create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        setNotify(`${create_time} ${username}`,
            `<p class="notifyContent"><span class="warnText">你的订单已被拒绝，请核对订单信息后再次提交${msg && `（${msg}）`|| ''}！</span></p>`,
            [{username}])
        jsonfile.writeFileSync(`data/order/${today}.json`, listObject)
        res.send({
            code: 0,
            msg: '操作成功',
        })
    },
    '/pass':(req, res)=>{
        let {price,code,name,platform,username}=req.body;
        if(!isArray(platform) || (!code && !name) || !price || !username) return res.send({code:1,msg:'平台、CODE、名称和价格不能为空'});
        platform=platform.filter(i=>i)
        const shopObject=platform.map((plat,index)=>{
            return jsonfile.readFileSync(`data/shop/${plat}.json`)
        })
        const today = moment().format('YYYY_MM_DD');
        platform.map((plat,index)=>{
            const valuse=flatten(Object.values(shopObject[index]).filter(i=>isArray(i)));
            const isUseName=shopObject[index].type;
            (isUseName?name:code).map((c,cIndex)=>{
                c.split(',').map((cc,ccIndex)=>{
                    const item={tag:"全部"};
                    //修改价格，名称
                    const findIndex=valuse.findIndex(i=>isUseName?i.name===cc:i.code===cc)
                    if(findIndex < 0){
                        //未找到
                        item.name=name[cIndex].split(',')[ccIndex];
                        item.price=Number(price[cIndex].split(',')[ccIndex]);
                        !isUseName && (item.code=cc);
                        if(!shopObject[index]["全部"]){
                            shopObject[index]["全部"]=[item];
                        }else {
                            shopObject[index]["全部"].push(item);
                        }
                    }
                })
            });
            jsonfile.writeFileSync(`data/shop/${platform}.json`, shopObject[index])
        });
        //审核通过
        const listObject = jsonfile.readFileSync(`data/order/${today}.json`)
        listObject[username].isAudit=listObject[username].isAudit.map(i=>1);
        jsonfile.writeFileSync(`data/order/${today}.json`, listObject);
        res.send({
            code: 0,
            msg: '操作成功',
        })
    },
    '/set':(req, res)=>{
        //orderType 1按钮提交
        let {username,price,code,name,platform,tag,remark,type,status,senduser='',note,orderType,operateUser}=req.body;
        let inputLog,outPutLog;
        const today = moment().format('YYYY_MM_DD');
        const create_time = moment().format('YYYY-MM-DD HH:mm:ss');
        if(!platform || !username) return res.send({code:1,msg:'平台和用户名不能为空'});
        let shopObject;
        if(isArray(platform)){
            shopObject=platform.map((plat,index)=>{
                if(!plat) return {};
                return jsonfile.readFileSync(`data/shop/${plat}.json`)
            })
        }else {
            shopObject= jsonfile.readFileSync(`data/shop/${platform}.json`)
        }
        operateUser=operateUser || username
        let listObject={},checkJson={isAudit:[]};
        try {
            listObject=jsonfile.readFileSync(`data/order/${today}.json`)
        }catch{}
        const usersInfo=jsonfile.readFileSync(`data/user.json`)
        let balance=usersInfo[username] && usersInfo[username].balance
        let sendUserBalance=senduser && senduser.map(k=>usersInfo[k].balance)
        const userOrder=listObject[username]
        if(userOrder) {
            if(userOrder.operateUser && userOrder.operateUser!==operateUser){
                return res.send({
                    code: 1,
                    msg: '订单类型为个人订单',
                });
            }
            if(userOrder.senduser){
                //禁止订单类型转换
                const userLen=userOrder.senduser.length
                if(!senduser){
                    return res.send({
                        code: 1,
                        msg: `订单类型为${userLen===1?'代点':'拼团'}订单`,
                    });
                }else {
                    const isDifference=difference(userOrder.senduser,senduser)
                    if(userLen===1 && isDifference.length){
                        return res.send({
                            code: 1,
                            msg: '订单类型为代点订单',
                        });
                    }
                }
            }
            if(userOrder.status){
                return res.send({
                    code: 1,
                    msg: '订单已锁定，请联系管理员解锁',
                });
            }
        }
        //已经拼团订单禁止点击
        if(senduser){
            const hadUser=senduser.find(user=>listObject[user] && listObject[user].platform && user!==username)
            if(hadUser) return res.send({
                code: 1,
                msg: `${hadUser}已经点餐，不能参加拼团订单`,
            });
        }else {
            //正在拼团订单,发起username不是自己
            const allSenduser=Object.values(listObject).map(i=>i.senduser).filter(i=>i)
            const hadOrderUser=allSenduser.find(item=>item.includes(username))
            if(hadOrderUser) return res.send({
                code: 1,
                msg: `已存在拼团订单`,
            });
        }
        //校验价格code不会变
        const suffix=!isUndefined(type) && `（${status?'修改':'添加'}${orderTimeMap[type]}）`;
        if(senduser){
            const prefix=senduser.length===1?'代点订单':'拼团订单';
            inputLog=`${username}${userOrder && userOrder.platform?'修改':'创建'}${prefix}${suffix || ''}（${senduser}）<span>${code ||''}</span><span>${name ||''}</span><span>${price||''}</span></p>`
        }else {
            inputLog=`${username}${userOrder && userOrder.platform?'修改':'创建'}订单${suffix || ''}<span>${code ||''}</span><span>${name ||''}</span><span>${price||''}</span>，余额为${balance}</p>`
        }
        const orderParamsMap=["name","code","price"];
        //下单方式一，读取code，错误删除订单重新下单
        if(isArray(platform)){
            //数据重写
            platform.some((plat,index)=>{
                price[index]=price[index] || "0"
                name[index]=name[index] || ""
                code[index]=code[index] || ""
                if(userOrder && userOrder.platform){
                    userOrder.platform[index]=plat
                }
                if(!plat) return;
                let realOrderInfo;
                const isShopUse=shopObject[index].isReady
                const values=flatten(Object.values(shopObject[index]).filter(i=>isArray(i)))
                const isUseName=shopObject[index].type
                if(isShopUse){
                    if(isUseName){
                        realOrderInfo=name[index].split(',').map(c=>{
                            return values.find(i=>i.name===c)
                        })
                    }else {
                        realOrderInfo=code[index].split(',').map(c=>{
                            return values.find(i=>i.code===c)
                        })
                    }
                    //true，未找到订单信息
                    if(realOrderInfo.some(i=>!i)){
                        return res.send({code: 1,msg:`未找到相关菜单，请重新输入${isUseName?'名称':'CODE'}`})
                    }
                    name[index]=realOrderInfo.map(i=>i.name).join(',')
                    price[index]=realOrderInfo.map(i=>i.price).join(',')
                }else {
                    //查看审核单,默认审核通过
                    checkJson.isAudit[index]=1;
                    if(shopObject[index]["全部"]){
                        const useResult=(isUseName?name:code)[index].split(',').map((cc,ccIndex)=>{
                            const result=shopObject[index]["全部"].find(j=>isUseName?j.name===cc:j.code===cc)
                            //重新赋为正确的值
                            name[index]=name[index]?name[index].split(',').map((a,aindex)=>{
                                return result?result.name:(a || "")
                            }).join(','):"";
                            price[index]=price[index].split(',').map((a,aindex)=>{
                                return result?result.price:(a || 0)
                            }).join(',');
                            if(!result){
                                //存在未找到的单，继续审核
                                checkJson.isAudit[index]=0;
                            }
                            return result?(isUseName?result.name:result.code):(cc || "")
                        })
                        if(isUseName){
                            name[index]=useResult
                        }else {
                            code[index]=useResult
                        }
                    }else {
                        checkJson.isAudit[index]=0;
                    }
                }
            })
            //价格计算
            if(userOrder && userOrder.platform){
                let itemPrice=userOrder.itemPrice || 0,spread=0;
                const oldBalance=eval(userOrder.price.map(p=>eval(p.split(',').join('+'))).join('+'));
                const newBalance=eval(price.map(p=>eval(p.split(',').join('+'))).join('+'));
                if(senduser){
                    spread= Math.ceil(newBalance/sendUserBalance.length) - itemPrice
                    sendUserBalance=sendUserBalance.map(i=>(i - spread))
                    // 余额均分计算
                    const returnMasterInfo=!userOrder.senduser && `，退回转换订单金额 ${oldBalance} ` || "";
                    const spreadInfo=spread <0 && `，退回金额 ${Math.abs(spread)}` || spread >0 && `，扣除金额 ${Math.abs(spread)}` || ''
                    const cancelUser=difference(userOrder.senduser,senduser)
                    const addUser=difference(senduser,userOrder.senduser)
                    //互斥关系 senduser ，cancelUser. addUser
                    remark=userOrder.senduser?senduser.map((user,index)=>{
                        if(userOrder.senduser.includes(user)){
                            const oldUserBalance=usersInfo[user].balance
                            if(username===user){
                                userOrder.balance=sendUserBalance[index]
                                usersInfo[user].balance=sendUserBalance[index]
                                return `${user}（余额：${oldUserBalance}${spreadInfo}）扣除拼团订单均分金额 ${itemPrice + spread} 后余额为 ${sendUserBalance[index]}`

                            }else {
                                usersInfo[user].balance=sendUserBalance[index];
                                return `${user}（余额：${oldUserBalance}${spreadInfo}）扣除拼团订单均分金额 ${itemPrice + spread} 后余额为 ${sendUserBalance[index]}`

                            }
                        }
                    }):[username].map((user,index)=>{
                        const oldUserBalance=usersInfo[user].balance
                        userOrder.balance=oldUserBalance+oldBalance
                        usersInfo[user].balance=oldUserBalance+oldBalance
                        return `${user}（余额：${oldUserBalance}）${returnMasterInfo}后余额为 ${userOrder.balance}`
                    });
                    //不包含,退回余额
                    if(cancelUser.length){
                        cancelUser.map(user=>{
                            const oldSenduserBalance=usersInfo[user].balance
                            usersInfo[user].balance=usersInfo[user].balance + itemPrice;
                            remark.unshift(`${user}（余额：${oldSenduserBalance}） 退出拼团订单，退回余额 ${itemPrice}，余额为 ${usersInfo[user].balance}`)
                        })
                    }
                    // 新加入
                    if(addUser.length){
                        addUser.map(user=>{
                            const oldSenduserBalance=usersInfo[user].balance
                            usersInfo[user].balance=usersInfo[user].balance - itemPrice - spread;
                            remark.unshift(`${user}（余额：${oldSenduserBalance}） 加入拼团订单，扣除余额 ${itemPrice + spread}，余额为 ${usersInfo[user].balance}`)
                        })
                    }
                    userOrder.itemPrice=itemPrice + spread
                    userOrder.senduser=senduser
                    userOrder.remark=remark
                }else {
                    balance= balance + oldBalance - newBalance;
                    userOrder.balance=balance
                }
                orderParamsMap.map(k=>{
                    userOrder[k]=eval(k)
                });
                userOrder.note=note
                userOrder.operateUser=operateUser
                listObject[username]={...userOrder,...checkJson}
            }else {
                const orderBalance=eval(price.map(p=>eval(p.split(',').join('+'))).join('+'))
                let itemPrice=0;
                if(senduser){
                    //现100原50 50/5，每人减10；现50原100，没人加10
                    itemPrice=Math.ceil(orderBalance/sendUserBalance.length);
                    sendUserBalance=sendUserBalance.map(i=>(i - itemPrice));
                    remark=senduser.map((user,index)=>{
                        const oldUserBalance=usersInfo[user].balance
                        usersInfo[user].balance=sendUserBalance[index];
                        if(user===username){
                            balance=sendUserBalance[index];
                        }
                        return `${user}（余额：${oldUserBalance}）扣除拼团订单均分金额 ${itemPrice} 后余额为 ${sendUserBalance[index]}`
                    })
                }else {
                    balance=balance-orderBalance
                }
                const balanceInfo=userOrder && userOrder.balanceInfo || [];
                listObject[username]={...checkJson,balanceInfo,operateUser,platform,username,create_time,senduser,price,code,name,balance,itemPrice,remark,note,status:0,tag}
            }
        }else {
            //商家页面直接下单,统一数据处理格式
            price=set([],type,String(price))
            code=set([],type,code)
            name=set([],type,name)
            platform=set([],type,platform)
            //商家页面转换为拼团订单
            if(userOrder && userOrder.platform){
                if(userOrder.platform[type]){
                    //有订单 status 0添加 1替换
                    const newBalance=eval(price[type].split(',').join('+'));
                    if(status){
                        //余额操作1替换
                        const oldBalance=eval(userOrder.price[type].split(',').join('+'));
                        balance= balance + oldBalance - newBalance;
                        orderParamsMap.map(k=>{
                            set(userOrder[k],type,eval(k)[type])
                        });
                    }else {
                        //余额操作0添加或者原来有值
                        balance= balance - newBalance;
                        // 添加，原来有值
                        orderParamsMap.map(k=>{
                            const arr=(userOrder[k][type]).split(',');
                            arr.push(eval(k)[type]);
                            const newValue=arr.join(',');
                            set(userOrder[k],type,newValue);
                        });
                    }
                }else {
                    //无订单
                    const newBalance=eval(price[type].split(',').join('+'))
                    balance= balance - newBalance;
                    orderParamsMap.map(k=>{
                        set(userOrder[k],type,eval(k)[type])
                    });
                }
                userOrder.platform[type]=platform[type]
                userOrder.balance=balance
                userOrder.operateUser=operateUser
                listObject[username]={...userOrder,...checkJson}
            }else {
                let itemPrice=0;
                const newBalance=eval(price[type].split(',').join('+'));
                balance= balance - newBalance;
                const balanceInfo=userOrder && userOrder.balanceInfo || [];
                listObject[username]={...checkJson,balanceInfo,operateUser,platform,username,create_time,senduser,price,code,name,balance,itemPrice,remark,note,status:0,tag}
            }
        }
        if(senduser){
            const prefix=senduser.length===1?'代点订单':'拼团订单';
            outPutLog=`${username}生成${senduser?prefix:'订单'}${suffix || ''}（${senduser}）<span>${code || ''}</span><span>${name || ''}</span><span>${price}</span>${remark && (' [ '+remark.join('，')+' ] ') || ''}，余额为 ${balance}`
        }else {
            outPutLog=`${username}生成订单${suffix || ''}<span>${code || ''}</span><span>${name || ''}</span><span>${price}</span>${remark && (' [ '+remark.join('，')+' ] ') || ''}，余额为 ${balance}`
        }
        if(!senduser){
            usersInfo[username].balance=balance
        }
        jsonfile.writeFileSync(`data/user.json`,usersInfo)
        //写入订单
        setLog(username,inputLog,outPutLog,listObject)
        jsonfile.writeFileSync(`data/order/${today}.json`,listObject)
        res.send({
            code: 0,
            msg: '操作成功',
        })
    },

    '/del': (req, res) => {
        const today = moment().format('YYYY_MM_DD');
        const {username} = req.body
        const listObject = jsonfile.readFileSync(`data/order/${today}.json`)
        if (listObject[username]) {
            delete listObject[username]
            jsonfile.writeFileSync(`data/order/${today}.json`, listObject)
            res.send({
                code: 0,
                msg: '删除成功',
            })
        } else {
            res.send({
                code: 1,
                msg: '用户记录未找到',
            })
        }
    },
}
